package com.example.delicioushunter.view.activity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.delicioushunter.R;
import com.example.delicioushunter.control.databasecontrol.FoodControl;
import com.example.delicioushunter.control.supportcontrol.BitmapProcess;
import com.example.delicioushunter.control.supportcontrol.CameraProcess;
import com.example.delicioushunter.control.supportcontrol.DHSharedPreference;
import com.example.delicioushunter.control.supportcontrol.QuickAction;
import com.example.delicioushunter.model.database.DHDatabaseHelper;
import com.example.delicioushunter.model.object.ActionItem;
import com.example.delicioushunter.model.object.Food;
import com.samsung.android.sdk.pen.SpenSettingEraserInfo;
import com.samsung.android.sdk.pen.SpenSettingPenInfo;
import com.samsung.android.sdk.pen.SpenSettingSelectionInfo;
import com.samsung.android.sdk.pen.SpenSettingTextInfo;
import com.samsung.android.sdk.pen.document.SpenInvalidPasswordException;
import com.samsung.android.sdk.pen.document.SpenNoteDoc;
import com.samsung.android.sdk.pen.document.SpenObjectBase;
import com.samsung.android.sdk.pen.document.SpenObjectContainer;
import com.samsung.android.sdk.pen.document.SpenObjectImage;
import com.samsung.android.sdk.pen.document.SpenObjectTextBox;
import com.samsung.android.sdk.pen.document.SpenPageDoc;
import com.samsung.android.sdk.pen.document.SpenPageDoc.HistoryListener;
import com.samsung.android.sdk.pen.document.SpenPageDoc.HistoryUpdateInfo;
import com.samsung.android.sdk.pen.document.SpenPageDoc.ObjectListener;
import com.samsung.android.sdk.pen.document.SpenUnsupportedTypeException;
import com.samsung.android.sdk.pen.document.SpenUnsupportedVersionException;
import com.samsung.android.sdk.pen.engine.SpenColorPickerListener;
import com.samsung.android.sdk.pen.engine.SpenContextMenuItemInfo;
import com.samsung.android.sdk.pen.engine.SpenControlBase;
import com.samsung.android.sdk.pen.engine.SpenControlList;
import com.samsung.android.sdk.pen.engine.SpenControlListener;
import com.samsung.android.sdk.pen.engine.SpenFlickListener;
import com.samsung.android.sdk.pen.engine.SpenPageEffectListener;
import com.samsung.android.sdk.pen.engine.SpenSurfaceView;
import com.samsung.android.sdk.pen.engine.SpenTextChangeListener;
import com.samsung.android.sdk.pen.engine.SpenTouchListener;
import com.samsung.android.sdk.pen.settingui.SpenSettingEraserLayout;
import com.samsung.android.sdk.pen.settingui.SpenSettingEraserLayout.EventListener;
import com.samsung.android.sdk.pen.settingui.SpenSettingPenLayout;
import com.samsung.android.sdk.pen.settingui.SpenSettingTextLayout;

public class InfoFragment extends Fragment {

	private final int MODE_PEN = 0;
	private final int MODE_SELECT = 1;
	private final int MODE_TEXT = 2;
	private final int MODE_UNDO = 3;
	private final int MODE_REDO = 4;
	private final int MODE_PAGE = 5;
	private final int MODE_PREVIOUS = 6;
	private final int MODE_NEXT = 7;
	private final int MODE_IMAGE = 8;

	private final int CONTEXT_MENU_DELETE_ID = 10;
	private final int CONTEXT_MENU_GROUP_ID = 26;
	private final int CONTEXT_MENU_UNGROUP_ID = 27;
	private static final int CONTEXT_MENU_GALLERY = 11;
	private static final int CONTEXT_MENU_CAMERA = 12;
	private static final int REQUEST_CODE_IMAGE_GALLERY = 13;
	private static final int REQUEST_CODE_CAMERA_CAPTURE = 14;
	private static final int REQUEST_CODE_CROP_THUMB = 15;
	private static final int REQUEST_CODE_CROP_IMAGE = 16;
	private static final int REQUEST_CODE_CROP_STEP = 25;

	private static final int ID_BUBBLE01 = 17;
	private static final int ID_BUBBLE02 = 18;
	private static final int ID_BUBBLE03 = 19;
	private static final int ID_CHARACTER01 = 20;
	private static final int ID_CHARACTER02 = 21;
	private static final int ID_CHARACTER03 = 22;
	private static final int ID_CHARACTER04 = 23;
	private static final int ID_CHARACTER05 = 24;
	/**
	 * Spen Objects
	 */
	private SpenNoteDoc mSpenNoteDoc;
	private SpenPageDoc mSpenPageDoc;
	private SpenSurfaceView mSpenSurfaceView;
	private SpenSettingPenLayout mSpenSettingView;
	private SpenSettingTextLayout mTextSettingView;
	private SpenSettingEraserLayout mEraserSettingView;
	private SpenObjectTextBox txtFoodName;
	private SpenObjectImage imgFoodImage, imgFoodThumb, imgStep;
	private SpenObjectImage selectedImage;
	/**
	 * Views
	 */
	private View rootView;
	private FrameLayout frame_container;
	private RelativeLayout spenViewLayout;
	private ImageView imgPen, imgEraser, imgSelect, imgText, imgUndo, imgRedo,
			imgAddPage, imgPrevious, imgNext, imgImage;
	private TextView txtSpenPage;
	private int index = 0;

	/**
	 * Properties
	 */
	private Rect rect;
	private int mMode = MODE_PEN;
	boolean isSpenFearureEnabled = false;
	private Context mContext;
	private SQLiteDatabase wdb;
	private SQLiteDatabase rdb;
	private DHDatabaseHelper helper;
	private Uri picUri;
	private int _id;
	private Food food;
	private FoodControl control;
	private Bitmap bitThumb;
	private ProgressDialog pd;
	private DHSharedPreference shared;
	private int icon;
	private BitmapProcess process;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mContext = getActivity();
		rootView = inflater.inflate(R.layout.fragment_info, container, false);
		shared = new DHSharedPreference(mContext);
		isSpenFearureEnabled = shared.getIsSpenFeatureEnabled();
		process = new BitmapProcess();

		try{
		buildPage();
		loadView();
		}catch(Exception e){
			e.printStackTrace();
			getActivity().finish();
		}
		setHasOptionsMenu(true);
		Log.d("Life", "Info - onCreate");
		return rootView;
	}

	private void loadView() {
		imgPen = (ImageView) rootView.findViewById(R.id.imgPen);
		imgEraser = (ImageView) rootView.findViewById(R.id.imgEraser);
		imgSelect = (ImageView) rootView.findViewById(R.id.imgSelect);
		imgText = (ImageView) rootView.findViewById(R.id.imgText);
		imgUndo = (ImageView) rootView.findViewById(R.id.imgUndo);
		imgRedo = (ImageView) rootView.findViewById(R.id.imgRedo);
		imgAddPage = (ImageView) rootView.findViewById(R.id.imgAddPage);
		imgPrevious = (ImageView) rootView.findViewById(R.id.imgPrevious);
		imgNext = (ImageView) rootView.findViewById(R.id.imgNext);
		imgImage = (ImageView) rootView.findViewById(R.id.imgImage);
		txtSpenPage = (TextView) rootView.findViewById(R.id.txtSpenPage);

		imgPen.setOnTouchListener(imgPenTouch);
		imgEraser.setOnTouchListener(imgEraserTouch);
		imgSelect.setOnTouchListener(imgSelectTouch);
		imgText.setOnTouchListener(imgTextTouch);
		imgUndo.setOnTouchListener(imgUndoTouch);
		imgRedo.setOnTouchListener(imgRedoTouch);
		imgAddPage.setOnTouchListener(imgAddPageTouch);
		imgPrevious.setOnTouchListener(imgPreviousTouch);
		imgNext.setOnTouchListener(imgNextTouch);

		// Quick bar
		ActionItem picture_bubble01 = new ActionItem(ID_BUBBLE01, "Bubble01",
				getActivity().getResources()
						.getDrawable(R.drawable.ic_bubble01),
				R.drawable.picture_bubble01);
		ActionItem picture_bubble02 = new ActionItem(ID_BUBBLE02, "Bubble02",
				getActivity().getResources()
						.getDrawable(R.drawable.ic_bubble02),
				R.drawable.picture_bubble02);
		ActionItem picture_bubble03 = new ActionItem(ID_BUBBLE03, "Bubble03",
				getActivity().getResources()
						.getDrawable(R.drawable.ic_bubble03),
				R.drawable.picture_bubble03);
		ActionItem picture_character01 = new ActionItem(ID_CHARACTER01,
				"Character01", getActivity().getResources().getDrawable(
						R.drawable.ic_character01),
				R.drawable.picture_character01);
		ActionItem picture_character02 = new ActionItem(ID_CHARACTER02,
				"Character02", getActivity().getResources().getDrawable(
						R.drawable.ic_character02),
				R.drawable.picture_character02);
		ActionItem picture_character03 = new ActionItem(ID_CHARACTER03,
				"Character03", getActivity().getResources().getDrawable(
						R.drawable.ic_character03),
				R.drawable.picture_character03);
		ActionItem picture_character04 = new ActionItem(ID_CHARACTER04,
				"Character04", getActivity().getResources().getDrawable(
						R.drawable.ic_character04),
				R.drawable.picture_character04);
		ActionItem picture_character05 = new ActionItem(ID_CHARACTER05,
				"Character05", getActivity().getResources().getDrawable(
						R.drawable.ic_character05),
				R.drawable.picture_character05);

		final QuickAction mQuickAction = new QuickAction(mContext);

		mQuickAction.addActionItem(picture_bubble01);
		mQuickAction.addActionItem(picture_bubble02);
		mQuickAction.addActionItem(picture_bubble03);
		mQuickAction.addActionItem(picture_character01);
		mQuickAction.addActionItem(picture_character02);
		mQuickAction.addActionItem(picture_character03);
		mQuickAction.addActionItem(picture_character04);
		mQuickAction.addActionItem(picture_character05);

		mQuickAction
				.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
					@Override
					public void onItemClick(QuickAction quickAction, int pos,
							int actionId) {
						ActionItem actionItem = quickAction.getActionItem(pos);
						icon = actionItem.getThumb();
					}
				});

		mQuickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
			@Override
			public void onDismiss() {
			}
		});

		imgImage.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				selectButton(v);
				mMode = MODE_IMAGE;
				mQuickAction.show(v);
				mSpenSurfaceView.setToolTypeAction(SpenSurfaceView.TOOL_SPEN,
						SpenSurfaceView.ACTION_NONE);
				return false;
			}
		});

		txtSpenPage.setText("Page " + index);
	}

	private void loadFood() {
		helper = new DHDatabaseHelper(mContext);

		Intent intent = getActivity().getIntent();
		_id = Integer.parseInt(intent.getExtras().getString("ID"));

		control = new FoodControl();
		rdb = helper.getReadableDatabase();
		food = control.getFood(_id, rdb);
		bitThumb = food.getThumb();
	}

	private void loadNoteFile(String filePath) {
		try {
			SpenNoteDoc tmpSpenNoteDoc = new SpenNoteDoc(mContext, filePath,
					rect.width(), SpenNoteDoc.MODE_WRITABLE);
			mSpenNoteDoc.close();
			mSpenNoteDoc = tmpSpenNoteDoc;
			if (mSpenNoteDoc.getPageCount() == 0) {
				mSpenPageDoc = mSpenNoteDoc.appendPage();
			} else {
				mSpenPageDoc = mSpenNoteDoc.getPage(0);
			}
			mSpenSurfaceView.setPageDoc(mSpenPageDoc, true);

		} catch (IOException e) {
			Toast.makeText(mContext, "Cannot open this file.",
					Toast.LENGTH_LONG).show();
			getActivity().finish();
		} catch (SpenUnsupportedTypeException e) {
			Toast.makeText(mContext, "This file is not supported.",
					Toast.LENGTH_LONG).show();
			getActivity().finish();
		} catch (SpenInvalidPasswordException e) {
			Toast.makeText(mContext, "This file is locked by a password.",
					Toast.LENGTH_LONG).show();
			getActivity().finish();
		} catch (SpenUnsupportedVersionException e) {
			Toast.makeText(mContext,
					"This file is the version that does not support.",
					Toast.LENGTH_LONG).show();
			getActivity().finish();
		} catch (Exception e) {
			Toast.makeText(mContext, "Failed to load noteDoc.",
					Toast.LENGTH_LONG).show();
			getActivity().finish();
		}
	}

	private void buildPage() {

		frame_container = (FrameLayout) rootView
				.findViewById(R.id.frame_container);
		spenViewLayout = (RelativeLayout) rootView
				.findViewById(R.id.spenViewLayout);

		mSpenSettingView = new SpenSettingPenLayout(mContext, new String(),
				spenViewLayout);
		if (mSpenSettingView == null) {
			Log.d("Spen", "Can't create SpenSettingView");
			getActivity().finish();
		}

		mEraserSettingView = new SpenSettingEraserLayout(mContext,
				new String(), spenViewLayout);
		if (mEraserSettingView == null) {
			Toast.makeText(mContext, "Cannot create new EraserSettingView.",
					Toast.LENGTH_SHORT).show();
			getActivity().finish();
		}

		try{
		mTextSettingView = new SpenSettingTextLayout(mContext, new String(),
				new HashMap<String, String>(), spenViewLayout);
		}catch(Exception e){
			e.printStackTrace();
			getActivity().finish();
		}
		if (mTextSettingView == null) {
			Toast.makeText(mContext, "Cannot create new TextSettingView.",
					Toast.LENGTH_SHORT).show();
			getActivity().finish();
		}

		frame_container.addView(mSpenSettingView);
		frame_container.addView(mTextSettingView);
		frame_container.addView(mEraserSettingView);

		// Create Spen View
		mSpenSurfaceView = new SpenSurfaceView(mContext);
		if (mSpenSurfaceView == null) {
			Toast.makeText(mContext, "Cannot creat new SpenSurfaceView",
					Toast.LENGTH_SHORT).show();
			getActivity().finish();
		}
		spenViewLayout.addView(mSpenSurfaceView);
		mSpenSettingView.setCanvasView(mSpenSurfaceView);
		mTextSettingView.setCanvasView(mSpenSurfaceView);
		mEraserSettingView.setCanvasView(mSpenSurfaceView);

		// Get the dimensions of the screen
		Display display = getActivity().getWindowManager().getDefaultDisplay();
		rect = new Rect();
		display.getRectSize(rect);

		try {
			mSpenNoteDoc = new SpenNoteDoc(mContext, rect.width(),
					rect.height());

		} catch (IOException e) {
			Toast.makeText(mContext, "Cannot create new NoteDoc.",
					Toast.LENGTH_SHORT).show();
			e.printStackTrace();
			getActivity().finish();
		} catch (Exception e) {
			e.printStackTrace();
			getActivity().finish();
		}

		BuildDataTask task = new BuildDataTask();
		task.execute();
	}

	private class BuildDataTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			pd.dismiss();
		}

		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(getActivity(), R.style.MyDialogTheme);
			pd.setMessage("Loading..");
			pd.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				loadFood();
				// Create SpenPageDoc
				mSpenPageDoc = mSpenNoteDoc.appendPage();
				mSpenPageDoc.clearHistory();

				// Set SpenPageDoc to SpenSurfaceView
				mSpenSurfaceView.setPageDoc(mSpenPageDoc, true);

				if (isSpenFearureEnabled == false) {
					mSpenSurfaceView.setToolTypeAction(
							SpenSurfaceView.TOOL_FINGER,
							SpenSurfaceView.ACTION_STROKE);
					Toast.makeText(
							mContext,
							"Device is not support Spen. \n "
									+ "You can draw stroke with your finger",
							Toast.LENGTH_SHORT).show();
				}

				Log.d("Check", "Value :" + food.getInfo_spd_uri());
				if (!food.getInfo_spd_uri().equalsIgnoreCase("empty")) {
					Log.d("Check", "Loading..");
					mSpenPageDoc.removeAllObject();
					loadNoteFile(food.getInfo_spd_uri());
				} else {
					Log.d("Check", "Creating..");
					loadBackground(mSpenPageDoc);

					txtFoodName = new SpenObjectTextBox();
					txtFoodName.setText(food.getName());
					txtFoodName
							.setTextAlignment(SpenObjectTextBox.ALIGN_CENTER);
					txtFoodName.setFontSize(24);
					txtFoodName.setFont("sans-serif-light");
					txtFoodName
							.setBorderType(SpenObjectTextBox.BORDER_TYPE_DOT);
					txtFoodName.setRect(new RectF(220, 60, 580, 100), false);
					txtFoodName.setMovable(false);
					txtFoodName.setRotatable(false);

					imgFoodImage = new SpenObjectImage();
					Bitmap bitFoodImage = BitmapFactory.decodeResource(
							getResources(), R.drawable.ic_food_image);
					bitFoodImage = process.addBorder(bitFoodImage, 10);
					imgFoodImage.setRect(new RectF(58, 180, 478, 600), false);
					imgFoodImage.setImage(bitFoodImage);
					imgFoodImage.setMovable(false);
					imgFoodImage.setRotatable(false);
					imgFoodImage.setMaxSize(420, 420);
					imgFoodImage.setMinSize(420, 420);

					imgFoodThumb = new SpenObjectImage();
					Bitmap bitFoodThumb = food.getThumb();
					bitFoodThumb = process.addBorder(bitFoodThumb, 5);
					imgFoodThumb.setRect(new RectF(483, 180, 747, 600), false);
					imgFoodThumb.setImage(bitFoodThumb);
					imgFoodThumb.setMovable(false);
					imgFoodThumb.setRotatable(false);
					imgFoodThumb.setMaxSize(264, 420);
					imgFoodThumb.setMinSize(264, 420);

					mSpenPageDoc.appendObject(txtFoodName);
					mSpenPageDoc.appendObject(imgFoodImage);
					mSpenPageDoc.appendObject(imgFoodThumb);
					mSpenSurfaceView.update();
					bitFoodImage.recycle();
					bitFoodThumb.recycle();
					bitFoodImage = null;
					bitFoodThumb = null;
				}

				mSpenSurfaceView.setColorPickerListener(mColorPickerListener);
				mSpenSurfaceView.setTouchListener(mPenTouchListener);
				mSpenSurfaceView.setControlListener(mControlListener);
				mSpenSurfaceView.setTextChangeListener(mTextChangeListener);
				mEraserSettingView.setEraserListener(mEraserListener);
				mSpenSurfaceView.setZoomable(false);
				mSpenPageDoc.setHistoryListener(mHistoryListener);
				mSpenPageDoc.setObjectListener(mSpenObjectListener);
				mSpenSurfaceView.setFlickListener(mFlickListener);
				initPenSettingInfo();

			} catch (Exception e) {
				e.printStackTrace();
				getActivity().finish();
			}
			return null;
		}
	}

	private ObjectListener mSpenObjectListener = new ObjectListener() {

		@Override
		public void onObjectRemoved(SpenPageDoc page,
				ArrayList<SpenObjectBase> objectList, int type) {
			if (objectList.get(0).equals(txtFoodName)) {
				txtFoodName = new SpenObjectTextBox();
				txtFoodName.setText("The food name");
				txtFoodName.setTextAlignment(SpenObjectTextBox.ALIGN_CENTER);
				txtFoodName.setFontSize(24);
				txtFoodName.setFont("sans-serif-light");
				txtFoodName.setBorderType(SpenObjectTextBox.BORDER_TYPE_DOT);
				txtFoodName.setRect(new RectF(220, 60, 580, 100), false);
				txtFoodName.setMovable(false);
				txtFoodName.setRotatable(false);

				page.appendObject(txtFoodName);
				mSpenSurfaceView.update();
			}

		}

		@Override
		public void onObjectChanged(SpenPageDoc page,
				SpenObjectBase objectList, int type) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onObjectAdded(SpenPageDoc page,
				ArrayList<SpenObjectBase> objectList, int type) {
			if (index == 0) {
				if (objectList.get(0).getRect().top < 600) {
					mSpenPageDoc.removeObject(objectList.get(0));
					mSpenSurfaceView.update();
				}
			} else {
				if (objectList.get(0).getRect().top < 330) {
					mSpenPageDoc.removeObject(objectList.get(0));
					mSpenSurfaceView.update();
				}
			}

		}
	};

	private void loadBackground(SpenPageDoc mPage) {
		String root = getActivity().getExternalCacheDir().toString();
		File myDir = new File(root + "/Delicious Hunter/Background");
		myDir.mkdirs();

		String filePath = myDir.listFiles()[0].getAbsolutePath();
		mPage.setBackgroundImage(filePath);
	}

	private HistoryListener mHistoryListener = new HistoryListener() {
		@Override
		public void onCommit(SpenPageDoc page) {
		}

		@Override
		public void onUndoable(SpenPageDoc page, boolean undoable) {
			imgUndo.setEnabled(undoable);
		}

		@Override
		public void onRedoable(SpenPageDoc page, boolean redoable) {
			imgRedo.setEnabled(redoable);
		}
	};

	private SpenColorPickerListener mColorPickerListener = new SpenColorPickerListener() {

		@Override
		public void onChanged(int color, int x, int y) {
			if (mSpenSettingView != null) {
				SpenSettingPenInfo info = mSpenSettingView.getInfo();
				info.color = color;
				mSpenSettingView.setInfo(info);
			}
		}
	};

	private SpenTouchListener mPenTouchListener = new SpenTouchListener() {

		@Override
		public boolean onTouch(View view, MotionEvent event) {
			closeSettingView();
			if (event.getAction() == MotionEvent.ACTION_UP
					&& event.getToolType(0) == SpenSurfaceView.TOOL_SPEN) {
				SpenControlBase control = mSpenSurfaceView.getControl();
				if (control == null) {
					if (mMode == MODE_IMAGE) {
						SpenObjectImage imgObj = new SpenObjectImage();
						Bitmap imageBitmap = BitmapFactory.decodeResource(
								mContext.getResources(), icon);
						imgObj.setImage(imageBitmap);

						float x = event.getX();
						float y = event.getY();
						float panX = mSpenSurfaceView.getPan().x;
						float panY = mSpenSurfaceView.getPan().y;
						float zoom = mSpenSurfaceView.getZoomRatio();
						float imgWidth = imageBitmap.getWidth() * zoom;
						float imgHeight = imageBitmap.getHeight() * zoom;
						RectF imageRect = new RectF();
						imageRect.set((x - imgWidth / 2) / zoom + panX,
								(y - imgHeight / 2) / zoom + panY,
								(x + imgWidth / 2) / zoom + panX,
								(y + imgHeight / 2) / zoom + panY);
						imgObj.setRect(imageRect, true);
						mSpenPageDoc.appendObject(imgObj);
						mSpenSurfaceView.update();

						imageBitmap.recycle();

						mSpenSurfaceView.setToolTypeAction(
								SpenSurfaceView.TOOL_SPEN,
								SpenSurfaceView.ACTION_NONE);
						mMode = MODE_PEN;
						return true;
					} else if (mSpenSurfaceView
							.getToolTypeAction(SpenSurfaceView.TOOL_SPEN) == SpenSurfaceView.ACTION_TEXT) {
						SpenObjectTextBox textObj = new SpenObjectTextBox();
						RectF rect = getRealPoint(event.getX(), event.getY(),
								0, 0);
						rect.right += 200;
						rect.bottom += 50;
						textObj.setRect(rect, true);
						mSpenPageDoc.appendObject(textObj);
						mSpenPageDoc.selectObject(textObj);
						mSpenSurfaceView.update();
					}
				}
			}
			return false;
		}
	};

	private OnTouchListener imgEraserTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (mSpenSurfaceView.getToolTypeAction(SpenSurfaceView.TOOL_SPEN) == SpenSurfaceView.ACTION_ERASER) {
				if (mEraserSettingView.isShown()) {
					mEraserSettingView.setVisibility(View.GONE);
				} else {
					mEraserSettingView
							.setViewMode(SpenSettingEraserLayout.VIEW_MODE_NORMAL);
					mEraserSettingView.setVisibility(View.VISIBLE);
				}
			} else {
				selectButton(v);
				mSpenSurfaceView.setToolTypeAction(SpenSurfaceView.TOOL_SPEN,
						SpenSurfaceView.ACTION_ERASER);
			}
			return false;
		}
	};

	private EventListener mEraserListener = new EventListener() {
		@Override
		public void onClearAll() {
			for (SpenObjectBase obj : mSpenPageDoc.getObjectList()) {
				if ((obj.getRect().top > 600 && index == 0)
						|| (obj.getRect().top > 330 && index > 0))
					mSpenPageDoc.removeObject(obj);
			}
			mSpenSurfaceView.update();
		}
	};

	private RectF getRealPoint(float x, float y, float width, float height) {
		float panX = mSpenSurfaceView.getPan().x;
		float panY = mSpenSurfaceView.getPan().y;
		float zoom = mSpenSurfaceView.getZoomRatio();
		width *= zoom;
		height *= zoom;
		RectF realRect = new RectF();
		realRect.set((x - width / 2) / zoom + panX, (y - height / 2) / zoom
				+ panY, (x + width / 2) / zoom + panX, (y + height / 2) / zoom
				+ panY);
		return realRect;
	}

	private SpenControlListener mControlListener = new SpenControlListener() {

		@Override
		public void onRotationChanged(float arg0, SpenObjectBase arg1) {
		}

		@Override
		public void onRectChanged(RectF arg0, SpenObjectBase arg1) {
		}

		@Override
		public void onObjectChanged(ArrayList<SpenObjectBase> arg0) {
		}

		@Override
		public boolean onMenuSelected(ArrayList<SpenObjectBase> objectList,
				int itemId) {
			SpenObjectContainer objContainer;
			switch (itemId) {
			case CONTEXT_MENU_DELETE_ID:
				for (SpenObjectBase obj : objectList) {
					mSpenPageDoc.removeObject(obj);
				}
				mSpenSurfaceView.closeControl();
				mSpenSurfaceView.update();
				break;
			case CONTEXT_MENU_GROUP_ID:
				objContainer = mSpenPageDoc.groupObject(objectList, false);
				mSpenSurfaceView.closeControl();
				mSpenPageDoc.selectObject(objContainer);
				mSpenSurfaceView.update();
				break;
			case CONTEXT_MENU_UNGROUP_ID:
				ArrayList<SpenObjectBase> objList = new ArrayList<SpenObjectBase>();
				for (SpenObjectBase selectedObj : objectList) {
					if (selectedObj.getType() == SpenObjectBase.TYPE_CONTAINER) {
						objContainer = (SpenObjectContainer) selectedObj;
						for (SpenObjectBase obj : objContainer.getObjectList()) {
							objList.add(obj);
						}
						mSpenPageDoc.ungroupObject(
								(SpenObjectContainer) selectedObj, false);
					}
				}
				mSpenSurfaceView.closeControl();
				mSpenPageDoc.selectObject(objList);
				mSpenSurfaceView.update();
				break;
			case CONTEXT_MENU_GALLERY:
				loadFromGallery();
				break;
			case CONTEXT_MENU_CAMERA:
				captureImage();
				break;
			}

			return true;
		}

		@Override
		public boolean onCreated(ArrayList<SpenObjectBase> objectList,
				ArrayList<Rect> relativeRectList,
				ArrayList<SpenContextMenuItemInfo> menu,
				ArrayList<Integer> styleList, int pressType, PointF point) {

			if (objectList.get(0).getType() == SpenObjectBase.TYPE_IMAGE) {
				if ((index == 0 && objectList.get(0).getRect().top <= 600)
						|| (index > 0 && objectList.get(0).getRect().top <= 330)) {
					selectedImage = null;
					selectedImage = (SpenObjectImage) objectList.get(0);
					menu.add(new SpenContextMenuItemInfo(CONTEXT_MENU_GALLERY,
							"Load Photo", true));
					menu.add(new SpenContextMenuItemInfo(CONTEXT_MENU_CAMERA,
							"Take Photo", true));
				} else
					menu.add(new SpenContextMenuItemInfo(
							CONTEXT_MENU_DELETE_ID, "Delete", true));
			} else {
				menu.add(new SpenContextMenuItemInfo(CONTEXT_MENU_DELETE_ID,
						"Delete", true));
			}

			if (objectList.size() > 1) {
				menu.add(new SpenContextMenuItemInfo(CONTEXT_MENU_GROUP_ID,
						"Group", true));
			}
			for (SpenObjectBase obj : objectList) {
				if (obj.getType() == SpenObjectBase.TYPE_CONTAINER) {
					menu.add(new SpenContextMenuItemInfo(
							CONTEXT_MENU_UNGROUP_ID, "Ungroup", true));
					break;
				}
			}
			if (objectList.size() == 1)
				return true;
			SpenControlList controlList = new SpenControlList(mContext,
					mSpenPageDoc);

			controlList.setObject(objectList);
			controlList.setGroup(false);
			mSpenSurfaceView.setControl(controlList);
			controlList.setContextMenu(menu);

			return true;
		}

		@Override
		public boolean onClosed(ArrayList<SpenObjectBase> objectList) {
			return false;
		}
	};

	private SpenFlickListener mFlickListener = new SpenFlickListener() {

		@Override
		public boolean onFlick(int direction) {
			int pageIndex = mSpenNoteDoc.getPageIndexById(mSpenPageDoc.getId());
			int pageCount = mSpenNoteDoc.getPageCount();
			if (pageCount > 1) {
				if (direction == DIRECTION_LEFT) {
					mSpenPageDoc = mSpenNoteDoc
							.getPage((pageIndex + pageCount - 1) % pageCount);
					mSpenSurfaceView.setPageDoc(mSpenPageDoc,
							SpenSurfaceView.PAGE_TRANSITION_EFFECT_LEFT,
							SpenSurfaceView.PAGE_TRANSITION_EFFECT_TYPE_SHADOW,
							0);

				} else if (direction == DIRECTION_RIGHT) {
					mSpenPageDoc = mSpenNoteDoc.getPage((pageIndex + 1)
							% pageCount);
					mSpenSurfaceView.setPageDoc(mSpenPageDoc,
							SpenSurfaceView.PAGE_TRANSITION_EFFECT_RIGHT,
							SpenSurfaceView.PAGE_TRANSITION_EFFECT_TYPE_SHADOW,
							0);
				}
				mSpenPageDoc.setObjectListener(mSpenObjectListener);
				index = mSpenNoteDoc.getPageIndexById(mSpenPageDoc.getId());
				txtSpenPage.setText("Page " + index);
				return true;
			}
			return false;
		}
	};

	private SpenTextChangeListener mTextChangeListener = new SpenTextChangeListener() {

		@Override
		public boolean onSelectionChanged(int arg0, int arg1) {
			return false;
		}

		@Override
		public void onMoreButtonDown(SpenObjectTextBox arg0) {
		}

		@Override
		public void onChanged(SpenSettingTextInfo info, int state) {
			if (mTextSettingView != null) {
				if (state == CONTROL_STATE_SELECTED) {
					mTextSettingView.setInfo(info);
				}
			}
		}

		@Override
		public void onFocusChanged(boolean arg0) {

		}
	};

	private void initPenSettingInfo() {
		SpenSettingPenInfo spenInfo = new SpenSettingPenInfo();
		spenInfo.color = Color.RED;
		spenInfo.size = 10;
		mSpenSurfaceView.setPenSettingInfo(spenInfo);
		mSpenSettingView.setInfo(spenInfo);

		SpenSettingTextInfo textInfo = new SpenSettingTextInfo();
		textInfo.size = 30;
		mSpenSurfaceView.setTextSettingInfo(textInfo);
		mTextSettingView.setInfo(textInfo);

		SpenSettingEraserInfo eraserInfo = new SpenSettingEraserInfo();
		eraserInfo.size = 30;
		mSpenSurfaceView.setEraserSettingInfo(eraserInfo);
		mEraserSettingView.setInfo(eraserInfo);

		SpenSettingSelectionInfo selectionInfo = new SpenSettingSelectionInfo();
		selectionInfo.type = SpenSettingSelectionInfo.TYPE_RECT;
		mSpenSurfaceView.setSelectionSettingInfo(selectionInfo);
	}

	// OnTouchListener
	private OnTouchListener imgPenTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			selectButton(v);
			if (mSpenSurfaceView.getToolTypeAction(SpenSurfaceView.TOOL_SPEN) == SpenSurfaceView.ACTION_STROKE) {
				if (mSpenSettingView.isShown()) {
					mSpenSettingView.setVisibility(View.GONE);
				} else {
					mSpenSettingView
							.setViewMode(SpenSettingTextLayout.VIEW_MODE_NORMAL);
					mSpenSettingView.setVisibility(View.VISIBLE);
				}
			} else {
				mMode = MODE_PEN;
				mSpenSurfaceView.setToolTypeAction(SpenSurfaceView.TOOL_SPEN,
						SpenSurfaceView.ACTION_STROKE);
			}

			return false;
		}
	};

	private OnTouchListener imgSelectTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			selectButton(v);
			if (mSpenSurfaceView.getToolTypeAction(SpenSurfaceView.TOOL_SPEN) != SpenSurfaceView.ACTION_SELECTION) {
				mMode = MODE_SELECT;
				mSpenSurfaceView.setToolTypeAction(SpenSurfaceView.TOOL_SPEN,
						SpenSurfaceView.ACTION_SELECTION);
			}
			return false;
		}
	};

	private OnTouchListener imgTextTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (mSpenSurfaceView.getToolTypeAction(SpenSurfaceView.TOOL_SPEN) == SpenSurfaceView.ACTION_TEXT) {
				if (mTextSettingView.isShown()) {
					mTextSettingView.setVisibility(View.GONE);
				} else {
					mTextSettingView
							.setViewMode(SpenSettingTextLayout.VIEW_MODE_NORMAL);
					mTextSettingView.setVisibility(View.VISIBLE);
				}
			} else {
				mMode = MODE_TEXT;
				selectButton(v);
				mSpenSurfaceView.setToolTypeAction(SpenSurfaceView.TOOL_SPEN,
						SpenSurfaceView.ACTION_TEXT);
			}
			return false;
		}
	};

	private OnTouchListener imgUndoTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			selectButton(v);
			mMode = MODE_UNDO;
			if (mSpenPageDoc == null) {
				return false;
			}

			if (mSpenPageDoc.isUndoable()) {
				HistoryUpdateInfo[] userData = mSpenPageDoc.undo();
				mSpenSurfaceView.updateUndo(userData);
			}
			return false;
		}
	};

	private OnTouchListener imgRedoTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			selectButton(v);
			mMode = MODE_REDO;
			if (mSpenPageDoc == null) {
				return false;
			}
			if (mSpenPageDoc.isRedoable()) {
				HistoryUpdateInfo[] userData = mSpenPageDoc.redo();
				mSpenSurfaceView.updateRedo(userData);
			}
			return false;
		}
	};

	private OnTouchListener imgAddPageTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			selectButton(v);
			mMode = MODE_PAGE;
			mSpenSurfaceView.closeControl();
			closeSettingView();
			v.setClickable(false);
			AddPageTask task = new AddPageTask();
			task.execute();
			return false;
		}
	};

	private class AddPageTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			try {
				mSpenPageDoc = mSpenNoteDoc.insertPage(mSpenNoteDoc
						.getPageCount());
				loadBackground(mSpenPageDoc);
				mSpenPageDoc.clearHistory();

				mSpenSurfaceView.setPageDoc(mSpenPageDoc,
						SpenSurfaceView.PAGE_TRANSITION_EFFECT_RIGHT,
						SpenSurfaceView.PAGE_TRANSITION_EFFECT_TYPE_SHADOW, 0);
				mSpenSurfaceView
						.setPageEffectListener(new SpenPageEffectListener() {

							@Override
							public void onFinish() {
								imgAddPage.setClickable(true);

							}
						});

				SpenObjectImage imgStep01 = new SpenObjectImage();
				Bitmap bitStep01 = BitmapFactory.decodeResource(getResources(),
						R.drawable.ic_step01);
				imgStep01.setRect(new RectF(148, 80, 398, 330), false);
				imgStep01.setImage(bitStep01);
				imgStep01.setMovable(false);
				imgStep01.setRotatable(false);
				imgStep01.setMaxSize(250, 250);
				imgStep01.setMinSize(250, 250);
				mSpenPageDoc.appendObject(imgStep01);

				SpenObjectImage imgStep02 = new SpenObjectImage();
				Bitmap bitStep02 = BitmapFactory.decodeResource(getResources(),
						R.drawable.ic_step02);
				imgStep02.setRect(new RectF(402, 80, 652, 330), false);
				imgStep02.setImage(bitStep02);
				imgStep02.setMovable(false);
				imgStep02.setRotatable(false);
				imgStep02.setMaxSize(250, 250);
				imgStep02.setMinSize(250, 250);
				mSpenPageDoc.appendObject(imgStep02);

				mSpenSurfaceView.update();
				mSpenSurfaceView.setColorPickerListener(mColorPickerListener);
				mSpenSurfaceView.setTouchListener(mPenTouchListener);
				mSpenSurfaceView.setControlListener(mControlListener);
				mSpenSurfaceView.setTextChangeListener(mTextChangeListener);
				mSpenSurfaceView.setZoomable(false);
				mSpenPageDoc.setHistoryListener(mHistoryListener);
				mSpenPageDoc.setObjectListener(mSpenObjectListener);
				mSpenSurfaceView.setFlickListener(mFlickListener);

				bitStep01.recycle();
				bitStep01 = null;
				bitStep02.recycle();
				bitStep02 = null;
				mSpenSurfaceView.setToolTypeAction(SpenSurfaceView.TOOL_SPEN,
						SpenSurfaceView.ACTION_NONE);
			} catch (Exception e) {
				e.printStackTrace();
				getActivity().finish();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			index = mSpenNoteDoc.getPageIndexById(mSpenPageDoc.getId());
			txtSpenPage.setText("Page " + index);
		}

	}

	private OnTouchListener imgPreviousTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			selectButton(v);
			mMode = MODE_PREVIOUS;
			mSpenSurfaceView.closeControl();
			closeSettingView();

			int pageIndex = mSpenNoteDoc.getPageIndexById(mSpenPageDoc.getId());
			int pageCount = mSpenNoteDoc.getPageCount();
			if (pageCount > 1) {
				mSpenPageDoc = mSpenNoteDoc.getPage((pageIndex + pageCount - 1)
						% pageCount);
				mSpenSurfaceView.setPageDoc(mSpenPageDoc,
						SpenSurfaceView.PAGE_TRANSITION_EFFECT_LEFT,
						SpenSurfaceView.PAGE_TRANSITION_EFFECT_TYPE_SHADOW, 0);
			}
			mSpenPageDoc.setObjectListener(mSpenObjectListener);
			index = mSpenNoteDoc.getPageIndexById(mSpenPageDoc.getId());
			txtSpenPage.setText("Page " + index);
			return false;
		}
	};

	private OnTouchListener imgNextTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			selectButton(v);
			mMode = MODE_NEXT;
			mSpenSurfaceView.closeControl();
			closeSettingView();
			int pageIndex = mSpenNoteDoc.getPageIndexById(mSpenPageDoc.getId());
			int pageCount = mSpenNoteDoc.getPageCount();
			if (pageCount > 1) {
				mSpenPageDoc = mSpenNoteDoc
						.getPage((pageIndex + 1) % pageCount);
				mSpenSurfaceView.setPageDoc(mSpenPageDoc,
						SpenSurfaceView.PAGE_TRANSITION_EFFECT_RIGHT,
						SpenSurfaceView.PAGE_TRANSITION_EFFECT_TYPE_SHADOW, 0);
			}
			mSpenPageDoc.setObjectListener(mSpenObjectListener);
			index = mSpenNoteDoc.getPageIndexById(mSpenPageDoc.getId());
			txtSpenPage.setText("Page " + index);
			return false;
		}
	};

	private String getFoodName() {
		for (SpenObjectBase m : mSpenNoteDoc.getPage(0).getObjectList()) {
			if (m.getType() == SpenObjectBase.TYPE_TEXT_BOX)
				return ((SpenObjectTextBox) m).getText();
		}
		return null;
	}

	private void saveNoteFile(String strFileName) {
		try {
			mSpenNoteDoc.save(strFileName);

			food.setName(getFoodName());
			food.setThumb(bitThumb);
			food.setInfo_spd_uri(strFileName);
			wdb = helper.getWritableDatabase();
			control.updateFood(food, wdb);
			Toast.makeText(mContext, "Update Successfully", Toast.LENGTH_SHORT)
					.show();
			loadFood();

		} catch (IOException e) {
			Toast.makeText(mContext, "Cannot save NoteDoc file.",
					Toast.LENGTH_SHORT).show();
			e.printStackTrace();
			getActivity().finish();
			return;
		} catch (Exception e) {
			e.printStackTrace();
			getActivity().finish();
			return;
		}
		return;
	}

	private void closeSettingView() {
		mSpenSettingView.setVisibility(SpenSurfaceView.GONE);
		mTextSettingView.setVisibility(View.GONE);
	}

	private void selectButton(View v) {
		imgPen.setSelected(false);
		imgSelect.setSelected(false);
		imgText.setSelected(false);
		imgImage.setSelected(false);
		imgUndo.setSelected(false);
		imgRedo.setSelected(false);
		imgPrevious.setSelected(false);
		imgNext.setSelected(false);
		imgAddPage.setSelected(false);

		v.setSelected(true);
		closeSettingView();
	}

	private void loadFromGallery() {
		try {
			Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
			galleryIntent.setType("image/*");
			startActivityForResult(galleryIntent, REQUEST_CODE_IMAGE_GALLERY);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(mContext, "Cannot find gallery.", Toast.LENGTH_SHORT)
					.show();
			e.printStackTrace();
			getActivity().finish();
		}
	}

	private void captureImage() {
		CameraProcess process = new CameraProcess();
		if (process.isDeviceSupportCamera(mContext)) {
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			startActivityForResult(intent, REQUEST_CODE_CAMERA_CAPTURE);
		} else
			Toast.makeText(mContext, "Cannot find camera.", Toast.LENGTH_SHORT)
					.show();
	}

	private void performCropImage() {
		try {
			Intent cropIntent = new Intent("com.android.camera.action.CROP");
			cropIntent.setDataAndType(picUri, "image/*");
			cropIntent.putExtra("crop", "true");
			cropIntent.putExtra("aspectX", 400);
			cropIntent.putExtra("aspectY", 400);
			cropIntent.putExtra("outputX", 400);
			cropIntent.putExtra("outputY", 400);
			cropIntent.putExtra("scale", true);
			cropIntent.putExtra("return-data", true);

			File f = new File(Environment.getExternalStorageDirectory(),
					"/temporary_holder.jpg");
			try {
				f.createNewFile();
			} catch (IOException ex) {
				Log.e("io", ex.getMessage());
				getActivity().finish();
			}

			Uri uri = Uri.fromFile(f);

			cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

			startActivityForResult(cropIntent, REQUEST_CODE_CROP_IMAGE);
		} catch (ActivityNotFoundException anfe) {
			String errorMessage = "Whoops - your device doesn't support the crop action!";
			Toast toast = Toast.makeText(mContext, errorMessage,
					Toast.LENGTH_SHORT);
			toast.show();
			getActivity().finish();
		}
	}

	private void performCropThumb() {
		try {
			Intent cropIntent = new Intent("com.android.camera.action.CROP");
			cropIntent.setDataAndType(picUri, "image/*");
			cropIntent.putExtra("crop", "true");
			cropIntent.putExtra("aspectX", 244);
			cropIntent.putExtra("aspectY", 400);
			cropIntent.putExtra("outputX", 244);
			cropIntent.putExtra("outputY", 400);
			cropIntent.putExtra("scale", true);
			cropIntent.putExtra("return-data", true);

			File f = new File(Environment.getExternalStorageDirectory(),
					"/temporary_holder.jpg");
			try {
				f.createNewFile();
			} catch (IOException ex) {
				Log.e("io", ex.getMessage());
				getActivity().finish();
			}

			Uri uri = Uri.fromFile(f);

			cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

			startActivityForResult(cropIntent, REQUEST_CODE_CROP_THUMB);
		} catch (ActivityNotFoundException anfe) {
			String errorMessage = "Whoops - your device doesn't support the crop action!";
			Toast toast = Toast.makeText(mContext, errorMessage,
					Toast.LENGTH_SHORT);
			toast.show();
			getActivity().finish();
		}
	}

	private void performCropStep() {
		try {
			Intent cropIntent = new Intent("com.android.camera.action.CROP");
			cropIntent.setDataAndType(picUri, "image/*");
			cropIntent.putExtra("crop", "true");
			cropIntent.putExtra("aspectX", 250);
			cropIntent.putExtra("aspectY", 250);
			cropIntent.putExtra("outputX", 250);
			cropIntent.putExtra("outputY", 250);
			cropIntent.putExtra("scale", true);
			cropIntent.putExtra("return-data", true);

			File f = new File(Environment.getExternalStorageDirectory(),
					"/temporary_holder.jpg");
			try {
				f.createNewFile();
			} catch (IOException ex) {
				Log.e("io", ex.getMessage());
				getActivity().finish();
			}

			Uri uri = Uri.fromFile(f);

			cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

			startActivityForResult(cropIntent, REQUEST_CODE_CROP_STEP);
		} catch (ActivityNotFoundException anfe) {
			String errorMessage = "Whoops - your device doesn't support the crop action!";
			Toast toast = Toast.makeText(mContext, errorMessage,
					Toast.LENGTH_SHORT);
			toast.show();
			getActivity().finish();
		}
	}

	private boolean isEqualImage(SpenObjectImage img1, int left, int top,
			int right, int bottom) {
		RectF rect1 = img1.getRect();
		if (rect1.left == left && rect1.right == right
				&& rect1.bottom == bottom && rect1.top == top)
			return true;
		return false;
	}

	private void performCrop() {
		if (index == 0) {
			if (isEqualImage(selectedImage, 58, 180, 478, 600))
				performCropImage();
			else if (isEqualImage(selectedImage, 483, 180, 747, 600))
				performCropThumb();
		}

		if (index > 0) {
			if (isEqualImage(selectedImage, 148, 80, 398, 330)
					|| isEqualImage(selectedImage, 402, 80, 652, 330))
				performCropStep();
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == getActivity().RESULT_OK) {
			if (data == null) {
				Toast.makeText(mContext, "Cannot find the image",
						Toast.LENGTH_SHORT).show();
				return;
			}

			if (requestCode == REQUEST_CODE_CAMERA_CAPTURE) {
				picUri = data.getData();
				performCrop();
			}

			if (requestCode == REQUEST_CODE_IMAGE_GALLERY) {
				picUri = data.getData();
				performCrop();
			}

			if (requestCode == REQUEST_CODE_CROP_THUMB) {
				String filePath = Environment.getExternalStorageDirectory()
						+ "/temporary_holder.jpg";

				Log.d("Check", "Thumb");
				Bitmap thePic = BitmapFactory.decodeFile(filePath);
				thePic = Bitmap.createScaledBitmap(thePic, 244, 400, false);
				bitThumb = thePic;
				thePic = process.addBorder(thePic, 5);
				selectedImage.setImage(thePic);
				mSpenSurfaceView.update();
				thePic.recycle();
				thePic = null;
			}

			if (requestCode == REQUEST_CODE_CROP_IMAGE) {
				String filePath = Environment.getExternalStorageDirectory()
						+ "/temporary_holder.jpg";
				Log.d("Check", "Image");
				Bitmap thePic = BitmapFactory.decodeFile(filePath);
				thePic = Bitmap.createScaledBitmap(thePic, 400, 400, false);
				thePic = process.addBorder(thePic, 5);
				selectedImage.setImage(thePic);
				mSpenSurfaceView.update();
				thePic.recycle();
				thePic = null;
			}

			if (requestCode == REQUEST_CODE_CROP_STEP) {
				String filePath = Environment.getExternalStorageDirectory()
						+ "/temporary_holder.jpg";
				Log.d("Check", "Image");
				Bitmap thePic = BitmapFactory.decodeFile(filePath);
				selectedImage.setImage(thePic);
				mSpenSurfaceView.update();
				thePic.recycle();
				thePic = null;
			}
		}
	}

	private void clearObject() {
		if (pd != null)
			pd.dismiss();
		if (mSpenSurfaceView != null) {
			mSpenSurfaceView.close();
			mSpenSurfaceView = null;
		}

		if (mSpenNoteDoc != null) {
			try {
				mSpenNoteDoc.close();
			} catch (Exception i) {
				Log.d("Spen", i.getMessage());
				getActivity().finish();
			}

			mSpenNoteDoc = null;
		}

		if (mSpenSettingView != null) {
			mSpenSettingView.close();
			mSpenSettingView = null;
		}

		if (mTextSettingView != null) {
			mTextSettingView.close();
			mTextSettingView = null;
		}
	}

	@Override
	public void onDetach() {
		// TODO Auto-generated method stub
		super.onDetach();
		clearObject();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		clearObject();
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		inflater.inflate(R.menu.edit_food, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_save:
			pd.dismiss();
			saveFood();
			break;
		case R.id.action_delete:
			pd.dismiss();
			deleteFood();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void saveFood() {
		File filePath = new File(getActivity().getExternalCacheDir()
				.getAbsolutePath() + "/Delicious Hunter/SPD/Info/");
		if (!filePath.exists()) {
			if (!filePath.mkdirs()) {
				Toast.makeText(mContext, "Save Path Creation Error",
						Toast.LENGTH_SHORT).show();
				return;
			}
		}

		String saveFilePath = filePath.getPath() + '/';
		String fileName = "info_" + _id + ".spd";
		saveFilePath += fileName;
		saveNoteFile(saveFilePath);
	}

	private void deleteFood() {
		if (!food.getInfo_spd_uri().equalsIgnoreCase("empty")) {
			Log.d("Check", food.getInfo_spd_uri());
			File file = new File(food.getInfo_spd_uri());
			if (file.exists())
				file.delete();
		}

		wdb = helper.getWritableDatabase();
		control.deleteFood(_id, wdb);
		Toast.makeText(mContext, "Delete Successfully", Toast.LENGTH_SHORT)
				.show();
		Intent data = new Intent();
		data.putExtra("FOOD_ID", String.valueOf(_id));
		getActivity().setResult(getActivity().RESULT_CANCELED, data);
		getActivity().finish();
	}

}
